package com.example.testsbjenkins.jucTest;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @author: lt
 * @date: 2022/7/8 11:04
 * @Description: TestCyclicBarrier 底层实现:基于ReentrantLock 的Condition来阻塞和通知线程
 */
public class TestCyclicBarrier {
    
    //模拟6个运动员 都到达运动场才可以 进行运动
    static void test1()  {
        System.out.println("等所有人都到达才能开始运动");
        CyclicBarrier cyclicBarrier = new CyclicBarrier(6,()->{
            System.out.println("所有人都到达开始运动");
        });

        for (int i = 0; i < 6; i++) {
            int num =i+1;
            System.out.println("同学" + num + "现在从大门出发，前往运动场");
            new Thread(()->{
                try {
                    Thread.sleep((long) (Math.random() *1000));
                    System.out.println("同学"+num+"已经到达指定位置,再此等待");
                    cyclicBarrier.await();
                    double v = Math.random() * 1000;
                    Thread.sleep((long) v);
                    System.out.println("同学"+num+"完成运动,耗时: "+v);
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
                
            }).start();
            
        }
        
        
    }
    
    
    public static void main(String[] args) throws BrokenBarrierException, InterruptedException {
        test1();
    }
}
